package com.tree.retrofit.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tree.retrofit.service.IGithubService;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName com.tree.retrofit.utils
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-06-04 22:54
 * @Version 1.0
 */
@Service
public class RetrofitUtil {
    @Value("${retrofit.base.url}")
    private String baseUrl;

    private Retrofit retrofit;


    @PostConstruct
    public void init(){
        ConnectionPool connectionPool = new ConnectionPool();
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(60_000, TimeUnit.MILLISECONDS)
                .readTimeout(60_000,TimeUnit.MILLISECONDS)
                .writeTimeout(60_000,TimeUnit.MILLISECONDS)
                .connectionPool(connectionPool).build();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,true);
        /**
         * 如果不包含的property，不抛出异常
         */
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl).client(okHttpClient)
                .addConverterFactory(JacksonConverterFactory.create(objectMapper))
                .build();
    }

    /**
     * 获取github api
     * @return
     */
    public IGithubService getGitHubApi(){
        return retrofit.create(IGithubService.class);
    }
}
